package com.hjk.waibao.mj.bean;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Invocation;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.File;

@Data
@AllArgsConstructor
public class SessionKey {
    public static final SymmetricCrypto SM4 = SmUtil.sm4(FileUtil.readBytes(new File("SM4_KEY")));
    public String userId;
    public long timestamp;

    static {
        StaticLog.info("sessionKey加密文件：" + new File("SM4_KEY").getAbsolutePath());
    }

    private SessionKey() {
    }

    public SessionKey(String userId) {
        this.userId = userId;
        timestamp = System.currentTimeMillis();
    }

    public String getKey() {
        return SM4.encryptHex(toJson().toString());
    }

    public JSONObject toJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userId);
        jsonObject.put("timestamp", timestamp);
        return jsonObject;
    }

    public static SessionKey getSessionKey(String userId) {
        return new SessionKey(userId);
    }

    public static SessionKey decrypt(String ciphertext) {
        try {
            return JSONObject.parseObject(SM4.decryptStr(ciphertext), SessionKey.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SessionKey getSessionKey(Invocation invocation) {
        String sessionKey = invocation.getController().getCookie("sessionKey");
        if (StrUtil.isBlankOrUndefined(sessionKey)) {
            sessionKey = invocation.getController().getHeader("sessionKey");
        }
        if (StrUtil.isBlankOrUndefined(sessionKey)) {
            return null;
        } else {
            invocation.getController().setCookie("sessionKey", sessionKey, 86400);
            return decrypt(sessionKey);
        }
    }

}
